#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
#include <mutex>
#include <cassert>
#include "../comm/util.hpp"
#include "../comm/log.hpp"
#include "oj_model.hpp"
#include "oj_view.hpp"
#include <jsoncpp/json/json.h>
#include "../comm/httplib.h" 

namespace ns_control
{
    using namespace std;
    using namespace ns_log;
    using namespace ns_util;
    using namespace ns_model;
    using namespace ns_view;
    using namespace httplib;

    // 提供服务的主机
    class Machine
    {
    public:
        std::string _ip; 
        int _port;
        uint64_t _load; 
        std::mutex* _mtx; // C++ 中的 mutex 是禁止拷贝的, 因此使用指针来做
    public:
        Machine():_ip(""), _port(0), _load(0), _mtx(nullptr)
        {}
        ~Machine()
        {}
        uint64_t Load()
        {
            uint64_t load = 0;
            if(_mtx) _mtx->lock();
            load = _load;
            if(_mtx) _mtx->unlock();
            return load;
        }
        void IncLoad()
        {
            if(_mtx) _mtx->lock();
            _load ++;
            if(_mtx) _mtx->unlock();
        }
        void DecLoad()
        {
            if(_mtx) _mtx->lock();
            _load --;
            if(_mtx) _mtx->unlock();
        }
        void ResetLoad()
        {
            if(_mtx) _mtx->lock();
            _load = 0;
            if(_mtx) _mtx->unlock();
        }
    };

    const std::string service_machine = "./conf/service_machine.conf";

    // 负载均衡器
    class LoadBlance
    {
    private:
        std::vector<Machine> machines;
        std::vector<int> online;
        std::vector<int> offline;
        std::mutex mtx;
    public:
        LoadBlance()
        {
            assert(LoadConf(service_machine));
        }
        ~LoadBlance()
        {}
    public:
        bool LoadConf(const std::string &Machine_conf)
        {
            // 加载配置文件, 并初始化 machines, online
            std::ifstream in(Machine_conf);
            if(!in.is_open())
            {
                LOG(FATAL) << "加载 " << Machine_conf << " 失败" << "\n";
                return false;
            }
            std::string line;
            while(std::getline(in, line))
            {
                std::vector<std::string> tokens;
                StringUtil::SplitString(line, &tokens, ":");
                if(tokens.size() != 2)
                {
                    LOG(WARNING) << "切分 " << line << " 失败" << "\n";
                    continue;
                }
                Machine m;
                m._ip = tokens[0];
                m._port = stoi(tokens[1].c_str());
                m._load = 0;
                m._mtx = new std::mutex();

                online.push_back(machines.size()); 
                machines.push_back(m);
            }
            in.close();
            return true;
        }
        void ShowMachine()
        {
            mtx.lock();
            cout << "在线的主机为: ";
            for(auto& id: online)
            {
                cout << id << " ";
            }
            cout << endl;
            cout << "离线的主机为: ";
            for(auto& id: offline)
            {
                cout << id << " ";
            }
            cout << endl;
            mtx.unlock();
        }
        bool SmartChoice(int *id, Machine** m)
        {
            // 1. 使用选择好的主机(更新该主机的负载)
            // 2. 离线该主机
            mtx.lock();
            int online_num = online.size();
            if(online_num == 0)
            {
                LOG(FATAL) << "hhh, 整个系统都挂了吧, 活该！！！(只能靠运维了)" << "\n";
                return false;
            }
            // 选择在线的 负载最小的 主机
            uint64_t min_load = machines[online[0]].Load();
            *m = &machines[online[0]];
            *id = online[0];
            for(size_t i = 0; i < online.size(); i++)
            {
                uint64_t curr_load = machines[online[i]].Load();
                if(curr_load < min_load)
                {
                    min_load = curr_load;
                    *id = online[i];
                    *m = &machines[online[i]];
                }
            }
            mtx.unlock();
            ShowMachine();
            return true;
        }
        bool OnlineMachine()
        {
            mtx.lock();
            online.insert(online.end(), offline.begin(), offline.end());
            offline.erase(offline.begin(), offline.end());
            mtx.unlock();
            LOG(INFO) << "所有的主机主机都上线了!" << "\n";
        }
        bool OfflineMachine(int which)
        {
            mtx.lock();
            // 从在线的主机中删去
            for(auto id = online.begin(); id != online.end(); id ++)
            {
                if(*id == which) 
                {
                    machines[which].ResetLoad();
                    online.erase(id);
                    offline.push_back(which);
                    break;
                }
            }
            mtx.unlock();
        }
    };

    // 核心业务逻辑控制器
    class Control
    {
    private:
        Model model_; // 提供后台数据 
        View view_; // 提供 html 渲染功能
        LoadBlance load_blance_; // 负载均衡器 
    public:
        Control()
        {}
        ~Control()
        {}
    public:
        void RecoveryMachine()
        {
            load_blance_.OnlineMachine();
        }
        // 根据所有题目列表数据构建网页, html 为输出型参数
        bool AllQuestions(string *html)
        {
            bool ret = true;
            vector<class Question> all;
            if(model_.GetAllQuestions(&all))
            {
                sort(all.begin(), all.end(), [](const class Question &q1, const class Question& q2){
                    return stoi(q1.number.c_str()) < atoi(q2.number.c_str());
                });
                // 获取所有题目信息，并构建成网页
                view_.AllExpandHtml(all, html);
            }
            else
            {
                ret = false;
                *html = "获取题目失败， 形成题目列表失败";
            }
            return ret;
        }
        // 根据某个题目数据构建相应网页
        bool Question(const string &number, string *html)
        {
            class Question q;
            bool ret = true;
            if(model_.GetOneQuestion(number, &q))
            {
                // 获取指定题目信息，并构建成网页
                view_.OneExpandHtml(q, html);
            }
            else
            {
                ret = false;
                *html = "指定题目" + number + "不存在";
            }
            return ret;
        }
        // 判题功能
        void Judge(const std::string& number, const std::string in_json, std::string *out_json) // 被 server 通过功能路由来找到 Judge
        {
            LOG(DEBUG) << in_json << "\nnumber " << number << std::endl;
            // 1. 根据传入的题目编号, 直接拿到对应的题目细节
            struct Question q;
            model_.GetOneQuestion(number, &q);

            // 2. in_json 进行反序列化, 得到 用户input 源代码等, input 不做处理
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            std::string code = in_value["code"].asString();

            // 3. 拼接用户的代码 + 测试用例代码, 形成新的代码 
            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            std::string compile_string = writer.write(compile_value);
            // 4. 选择负载最低的主机, 并能差错处理

            while(true)
            {
                int id = 0;
                Machine* m = nullptr;
                if(!load_blance_.SmartChoice(&id, &m))
                {
                    break;
                }
                LOG(INFO) << "主机选择成功!!!!  主机id: " << id << " 详细：" << m->_ip << " " << m->_port << "\n";
                Client cli(m->_ip, m->_port); // 发起请求
                m->IncLoad(); // 负载 ++
                if(auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    if(res->status == 200)// 状态码必须为 200
                    {
                        // 5. 将结果赋值给out_json
                        *out_json = res->body;
                        m->DecLoad(); // 负载 --
                        LOG(INFO) << "请求编译和运行服务成功..." << "\n";
                        break;
                    }
                    m->DecLoad(); // 负载 --
                }
                else
                {
                    //请求失败
                    LOG(INFO) << "主机请求失败, 主机id: " << id << " 详细：" << m->_ip << " " << m->_port << "\n";
                    load_blance_.OfflineMachine(id); // 离线这个主机 
                }
                load_blance_.ShowMachine();
            }
        }
    };
}